package com.cmy.web.controller;

import com.cmy.web.query.TestQuery;
import com.cmy.webCore.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;

/**
 * 测试控制器
 * @Validated 这个注解用来声明默认的校验组或者对类中的所有方法应用相同的校验组,用在方法>用在类,一般不用在类上
 * @Valid 支持嵌套可直接用在主要嵌套校验的字段上
 * @Author:Cmy
 * @Date:2022/11/21-16:34
 */
@Slf4j
@RestController
@RequestMapping("test")
@CacheConfig(cacheNames = "user")
public class TestController {

    /**
     * 测试Get
     */
    @GetMapping("echoGet")
    public R echoGet(@RequestParam(name="name") @NotBlank(message = "FIELD_CANNOT_BE_EMPTY") String name){
        return R.success(name);
    }

    /**
     * 测试post
     */
    @PostMapping("echoPost")
    public R echoPost(@RequestBody @Validated TestQuery testQuery){
        return R.success(testQuery);
    }

    /**
     * testCacheable
     * 对应查询,如果未命中,执行逻辑后会将结果缓存
     */
    @GetMapping("cacheable")
    @Cacheable(value = {"common"},cacheManager = "caffeineCacheManager",key = "#id")
    public R cacheable(@RequestParam(name="id") String id){
        log.debug("generator new id~");
        return R.success(id);
    }

    /**
     * testCacheEvict
     * 对应删除会将结果删除
     * allEntries = true 属性表示清空所有缓存 可对应清空方法
     */
    @GetMapping("cacheEvict")
    @CacheEvict(value = {"common"},cacheManager = "caffeineCacheManager",key = "#id")
    public R cacheEvict(@RequestParam(name="id") String id){
        log.debug("evict new id~");
        return R.success();
    }

    /**
     * testCachePut
     * 对应修改,保存 每次一定会刷新缓存 双写 这里会直接重新构建对应key的缓存
     * 一般来说使用旁路缓存模式 即先更新db然后删除缓存,从查询重新构建缓存
     */
    @GetMapping("cachePut")
    @CachePut(value = {"common"},cacheManager = "caffeineCacheManager",key = "#id")
    public R cachePut(@RequestParam(name="id") String id){
        log.debug("put new id~");
        id="new_"+id;
        return R.success(id);
    }







}

    